import React from 'react';
import { DragSource, DragSourceSpec, DropTarget, DropTargetSpec } from 'react-dnd';

let dragingIndex = -1;

const BodyRow = (props: any) => {
  const { index, isOver, connectDragSource, connectDropTarget, moveRow, ...restProps } = props;
  let { className } = restProps;
  if (isOver) {
    index > dragingIndex && (className += ' drop-over-downward');
    index < dragingIndex && (className += ' drop-over-upward');
  }
  return connectDragSource(connectDropTarget(<tr {...restProps} className={className} />));
};

const rowSource: DragSourceSpec<{ index: number }, { index: number }> = {
  beginDrag(props) {
    dragingIndex = props.index;
    return { index: props.index };
  },
};

const rowTarget: DropTargetSpec<{
  index: number;
  moveRow: (dragIndex: number, hoverIndex: number) => void;
}> = {
  drop(props, monitor) {
    const dragIndex = monitor.getItem().index;
    const hoverIndex = props.index;
    if (dragIndex === hoverIndex) {
      return;
    }
    props.moveRow(dragIndex, hoverIndex);
    monitor.getItem().index = hoverIndex;
  },
};

const DragableBodyRow = DropTarget('row', rowTarget, (connect, monitor) => ({
  connectDropTarget: connect.dropTarget(),
  isOver: monitor.isOver(),
}))(
  DragSource('row', rowSource, connect => ({
    connectDragSource: connect.dragSource(),
  }))(BodyRow),
);

export const handleMoveRow = (data: any[], dragIndex: number, hoverIndex: number) => {
  const newData = [...data];
  newData.splice(dragIndex, 1);
  newData.splice(hoverIndex, 0, data[dragIndex]);
  return newData;
};

export default DragableBodyRow;
